<template>
  <div>
    <div class="buttons">
      <el-input placeholder="商家ID/账号/名称" style="width:200px; float: left; margin-right: 10px"
                v-model="search"></el-input>
      <el-button type="primary" @click="getSupplier">查询</el-button>
      <el-button type="primary" @click="clear">清空</el-button>
      <el-button type="primary" @click="createForm('create')">新增</el-button>
      <template v-if="checkNum===1">
        <el-button type="primary" @click="createForm('update')" this.ruleForm>修改</el-button>
      </template>
      <el-button type="danger" @click="removeForm" v-if="checkNum >=1">删除</el-button>
    </div>
    <VTable
      v-if="tableData.code!==405"
      :tableData="tableData.data"
      :tableHeader="tableHeader"
      :tableHandle="tableHandle"
      :tableHandle1="tableHandle1"
      :tableHandle2="''"
      :selectRow="selectRow"
      :tableSort="tableSort"
      v-loading="listLoading">
    </VTable>
    <div class="page-wrap" v-if="tableData.data">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="tableData.data.size"
        layout="total, prev, pager, next, jumper"
        :total="tableData.data.total">
      </el-pagination>
    </div>
    <VForm :title="title" v-if="dialogVisible" moduleName="supplier">
      <template v-if="dialogModle==='supplier'">
        <Supplier :_ruleForm="ruleForm" :formType="formType" :getTableData="getTableData"></Supplier>
      </template>
      <template v-if="dialogModle==='brand'">
        <Brand :busId="busId" :getTableData="getTableData"></Brand>
      </template>
      <template v-if="dialogModle==='bank'">
        <Bank :ruleBankForm="ruleBankForm" :formType="formType" :getTableData="getTableData" :id="id"></Bank>
      </template>
    </VForm>
  </div>
</template>
<script>
  import VTable from '../../components/VTable.vue'
  import Supplier from './Supplier.vue'
  import VForm from '../../components/VForm'
  import Brand from '../../view/supplier/Brand.vue'
  import Bank from '../../view/supplier/Bank.vue'
  import axios from 'axios'
  import api from '../../store/api'
  var moment = require('moment')
  var format = require('../../util/util')
  import {mapState, mapGetters} from 'vuex'
  import * as types from '../../store/mutations-type'
  export default {
    data () {
      return {
        search: '',
        title: '新建',
        currentPage: 1,
        limit: 20,
        status: true,
        selection: [],
        listLoading: false,
        ruleBankForm: {
          bankName: '',
          bankAcount: '',
          bankAccountName: '',
          bankAddr: '',
          rowState: '1'
        },
        busId: '',
        id: '',
        dialogModle: '',
        ruleForm: {
          busName: '',
          busPassword: '',
          nickName: '',
          phone: '',
          sex: '',
          rowState: '',
          createTime: '',
          cityId: []
        },
        tableHandle: [
          {
            text: '绑定品牌', event: this.brand
          }],
        tableHandle1: [
          {
            text: '绑定银行卡', event: this.bank
          }],
        formType: 'create',
        tableHeader: [
          {prop: 'busName', label: '商家名称', order: 'descending'},
          {prop: 'nickName', width: 120, label: '商家昵称'},
          {prop: 'phone', label: '手机号码', width: 125},
          {prop: 'sex', label: '性别', width: 100, formatter: this.formatterSex},
          {prop: 'rowState', label: '状态', width: 100, formatter: this.formatterStatus},
          {prop: 'bankAcount', label: '银行卡绑定状态', width: 155, formatter: this.formatterBankstatus},
          {prop: 'createTime', label: '创建时间', width: 175, formatter: this.formatterCteatetime},
          {prop: 'cityName', label: '区域', formatter: this.formatterAddress},
          {prop: 'brandNamePath', label: '品牌', width: 300}
          /* {prop: 'birthday', label: '生日'} */
        ]
      }
    },
    components: {
      VTable,
      Supplier,
      VForm,
      Brand,
      Bank
    },
    methods: {
      brand (index, obj) {
        this.dialogModle = 'brand'
        this.busId = obj.id
        this.$store.dispatch(types.SUPPLIER_SHOW_FORM)
        this.title = '绑定品牌'
      },
      bank (index, obj) {
        this.dialogModle = 'bank'
        this.id = obj.id
        axios.get(api.bankGet + '/' + this.id)
          .then(response => {
            const result = response.data
            if (result.success) {
              if (result.data) {
                this.ruleBankForm['id'] = result.data.id
                this.ruleBankForm['bankName'] = result.data.bankName
                this.ruleBankForm['bankAcount'] = result.data.bankAcount
                this.ruleBankForm['bankAccountName'] = result.data.bankAccountName
                this.ruleBankForm['phone'] = result.data.phone
                this.ruleBankForm['bankAddr'] = result.data.bankAddr
                this.ruleBankForm['rowState'] = result.data.rowState.toString()
              } else {
                this.ruleBankForm = {
                  bankName: '',
                  bankAcount: '',
                  bankAccountName: '',
                  bankAddr: '',
                  rowState: '1'
                }
                this.ruleBankForm.id = this.id
              }
              this.$store.dispatch(types.SUPPLIER_SHOW_FORM)
            }
          })
        this.$store.dispatch(types.SUPPLIER_SHOW_FORM)
        this.title = '绑定银行卡'
      },
      /**
       * 时间格式化
       * @param row
       * @returns {string}
       */
      formatterCteatedata (row) {
        return moment(new Date(row.birthday)).format('YYYY-MM-DD')
      },
      formatterCteatetime (row) {
        return moment(new Date(row.createTime)).format('YYYY-MM-DD hh:mm:ss')
      },
      /**
       * 性别转换
       * @param row
       * @returns {string}
       */
      formatterSex (row) {
        return row.sex === '1' ? '男' : row.sex === '2' ? '女' : ''
      },
      /**
       * 状态转义
       * @param row
       * @returns {string}
       */
      formatterStatus (row) {
        return row.rowState === 1 ? '启用' : row.rowState === 0 ? '禁用' : ''
      },
      /**
       * 银行卡绑定状态
       * @param row
       * @returns {string}
       */
      formatterBankstatus (row) {
        return row.bankAcount !== null ? '已绑定' : '未绑定'
      },
      /**
       * 区域合并
       * @param row
       * @returns {string}
       */
      formatterAddress (row) {
        return row.cityPname + ',' + row.cityName
      },
      /**
       * 每页条数
       * @param val
       */
      handleSizeChange (val) {
        console.log(`每页 ${val} 条`)
      },
      /**
       * 翻页
       * @param val
       */
      handleCurrentChange (val) {
        this.currentPage = val
        this.getSupplier()
      },
      getTableData () {
        this.$store.dispatch(types.SUPPLIER_REQ_LIST, '?pageIndex=' + this.currentPage + '&pageSize=' + this.limit + '')
      },
      /**
       * 跳转到商家表单
       * @param handle
       */
      createForm (handle) {
        this.formType = handle
        this.dialogModle = 'supplier'
        if (handle === 'update') {
          this.title = '修改'
          this.getBus()
        } else {
          this.$store.dispatch(types.SUPPLIER_SHOW_FORM)
          this.title = '新建'
        }
      },
      /**
       * 选中行处理
       * @param selection //总共选中行
       * @param row // 选中行
       */
      selectRow (selection, row) {
        this.$store.dispatch(types.SUPPLIER_CHECK_NUM, selection.length)
        this.selection = selection
      },
      getBus () {
        axios.get(api.supplierGet + '/' + this.selection[0].id)
          .then(response => {
            const result = response.data
            if (result.success) {
              this.ruleForm.id = result.data.id
              this.ruleForm.busName = result.data.busName
              this.ruleForm.busPassword = result.data.busPassword
              this.ruleForm.nickName = result.data.nickName
              this.ruleForm.phone = result.data.phone
              this.ruleForm.sex = result.data.sex
              this.ruleForm.rowState = result.data.rowState.toString()
              this.ruleForm.cityId.push(result.data.cityPid)
              this.ruleForm.cityId.push(result.data.cityId)
              this.$store.dispatch(types.SUPPLIER_SHOW_FORM)
              console.log(this.ruleForm)
            }
          })
      },
      /**
       * 根据id查询数据
       */
      getSupplier () {
        let para = {
          pageIndex: this.currentPage,
          search: this.search,
          pageSize: this.limit
        }
        if (!this.search) {
          delete para.search
        }
        para = format.formatString(para)
        this.$store.dispatch(types.SUPPLIER_REQ_LIST, '?' + para)
      },
      clear () {
        this.search = ''
        this.getTableData()
      },
      /**
       * 删除操作
       */
      removeForm () {
        var ids = this.selection.map(item => item.id).toLocaleString()
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true
          let para = ids
          axios.delete(api.supplierDelete + '/' + para).then((response) => {
            var result = response.data
            if (result.success) {
              this.listLoading = false
              this.$message({
                message: '删除成功',
                type: 'success'
              })
            } else {
              this.$message.error({
                title: '错误',
                message: result.message
              })
            }
            this.getTableData()
          }, (err) => {
            this.$message.error({
              title: '错误',
              message: err.response.data.message
            })
            this.listLoading = false
          })
        })
      },
      /**
       * 表单初始化
       */
      initFormData () {
        for (var i in this.ruleForm) {
          this.ruleForm[i] = ''
        }
      },
      /**
       * 列表排序
       * @param column
       * @param prop
       * @param order
       */
      tableSort (column, prop, order) {
      },
      handleItemChange (val) {
        var length = val.length - 1
        if (val.length === 1) {
          this.options.map((item, index) => {
            if (item.id === val[length]) {
              this.flag.a = index
              return
            }
          })
          this.getCityLib(val[length])
            .then(result => {
              this.options[this.flag.a].children = result
            })
        }
      },
      getCityLib (id) {
        let url = api.cityLib
        url = id ? url + '?parentId=' + id : url
        return new Promise((resolve, reject) => {
          axios.get(url)
            .then(response => {
              const result = response.data
              if (result.success) {
                resolve(result.data)
              } else {
                reject(result)
              }
            })
        })
      }
    },
    updated () {
      if (this.tableData.code === 405) {
        this.$message.error({
          title: '错误',
          message: this.tableData.message
        })
      }
    },
    computed: {
      ...mapState({
        dialogVisible: state => state.supplier.dialogVisible,
        checkNum: state => state.supplier.checkNum
      }),
      ...mapGetters({
        tableData: 'supplier_tableData'
      })
    },
    mounted () {
      this.getTableData()
    }
  }
</script>
